<template>
  <div class="container-app">
    <div style="margin-bottom:15px;">
      <el-button v-if="hasAdd" size="small" type="success" @click="addLine"><i class="el-icon-plus"></i>{{addTitle}}</el-button>
      <el-button v-if="hasDel" size="small" type="danger" @click="removeLine"><i class="el-icon-delete"></i>{{delTitle}}</el-button>
      <el-button v-if="hasUpdate" size="small" type="primary" @click="changeLine"><i class="el-icon-edit-outline"></i>{{updateTitle}}</el-button>
      <span class="right-search">
        <el-input @change="findLine" v-model="findData" size="small" placeholder="输入关键字搜索" style="width:300px;">
          <el-button @click="findLine" slot="append" icon="el-icon-search"></el-button>
        </el-input>
      </span>
    </div>
    <el-table :data="tableData" tooltip-effect="dark" style="width: 100%" @selection-change="getRow" border>
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="name" label="角色名称"></el-table-column>
      <el-table-column prop="code" label="角色编码"></el-table-column>
      <el-table-column prop="remark" label="角色描述"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="viewLine(scope.row)">
            <i class="el-icon-check"></i> 查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="24" class="paging">
      <span>总条数：{{dataTotal}}</span>
      <el-pagination @current-change="changePage" :page-size="10" :total="dataTotal"
        background layout="prev, pager, next" style="float:right;"></el-pagination>
		</el-col>

    <!--对话操作-->
    <el-dialog :title="dialogTitle" :visible.sync="isDialog" width="30%" :before-close="handleClose" :close-on-click-modal='false'>
      <div class="details-container">
        <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="120px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input size="small" v-model="roleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="角色编码" prop="roleCode">
            <el-input size="small" v-model="roleForm.code"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input type="textarea" v-model="roleForm.remark"></el-input>
          </el-form-item>
          <el-form-item label="角色菜单权限" prop="roleMenu">
            <el-tree ref="tree" @check="checkMenu"
              v-model="roleForm.roleMenu"
              :data="controls" node-key="id"
              show-checkbox highlight-current
              :default-expanded-keys="ids"
              check-strictly
            >
            </el-tree>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" size="small"  @click="submitForm('roleForm')">保存</el-button>
        <el-button type="danger" size="small"  @click="cancleForm('roleForm')">取消</el-button>
      </span>
    </el-dialog>

    <!--查看详情-->
    <el-dialog title="权限角色详情" :visible.sync="isDetails" width="30%" :before-close="handleClose" :close-on-click-modal='false'>
      <div class="details-container">
        <el-form label-width="120px">
	        <el-form-item label="角色名称" prop="roleName">
	            <el-input size="small" v-model="roleName" readonly='true'></el-input>
	          </el-form-item>
	          <el-form-item label="角色编码" prop="roleCode">
	            <el-input size="small" v-model="roleCode" readonly='true'></el-input>
	          </el-form-item>
	          <el-form-item label="角色描述" prop="roleDesc">
	            <el-input type="textarea" v-model="roleDesc" readonly='true'></el-input>
	          </el-form-item>
	          <el-form-item label="角色菜单权限" prop="tree1">
	            <el-tree ref="tree1" :data="controls1" show-checkbox  node-key="id" check-strictly ></el-tree>
	          </el-form-item>
	      </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" size="small" @click="isDetails = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  getRoleMenu,
  removeRole,
  addRole,
  updateRole,
  lookRoleInfo } from '@/api/roleTable'
export default {
  name: 'jsgl',
  data() {
    return {
      dataPage: 1,
      dataTotal: 1,
      isDialog: false,
      isDetails: false,
      roleName: '',
      roleCode:'',
      roleDesc: '',
      tableData: [],
      checked: false,
      dialogTitle: '新增角色',
      roleData: [],
      removeIds: [],
      roleForm: {
        name: '',
        code: '',
        remark: '',
        roleMenu: []
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在100个字符以内', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入角色编码', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在100个字符以内', trigger: 'blur' }
        ],
        remark: [
          { required: false, message: '请输入角色名称', trigger: 'blur' },
          { max: 100, message: '长度在100个字符以内', trigger: 'blur' }
        ],
        roleMenu: [
          { type: 'array', required: true, message: '请至少选择一个权限', trigger: 'change' }
        ]
      },
      controls: [],
      controls1: [],
      userId: 1,
      ids: [],
      findData: '',
      hasAdd: false,
      hasDel: false,
      hasUpdate: false,
      addTitle: '新增',
      updateTitle: '修改',
      delTitle: '删除',
      isAllCho: []
    }
  },
  mounted() {
    this.getRoleList()
    this.getMenu()
    this.getJur()
  },
  methods: {
    getJur() {
      const self = this
      self.$store.dispatch('Juage', this.$store.clickMenuId).then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            if (item.type == '3') {
              self.hasAdd = true
              self.addTitle = item.title
            }
            if (item.type == '5') {
              self.hasDel = true
              self.delTitle = item.title
            }
            if (item.type == '4') {
              self.hasUpdate = true
              self.updateTitle = item.title
            }
          })
        } else if (res.code !== '507') {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    getMenu() {
      getRoleMenu().then(res => {
        if (res.code == '200') {
          res.data.forEach(item => {
            const tree = {}
            tree.id = item.id
            tree.label = item.title
            tree.children = []
            if (item.children && item.children.length) {
              item.children.forEach(item1 => {
                const tree1 = {}
                tree1.id = item1.id
                tree1.label = item1.title
                tree1.children = []
                if (item1.children && item1.children.length) {
                  item1.children.forEach(item2 => {
                    const tree2 = {}
                    tree2.id = item2.id
                    tree2.label = item2.title
                    tree1.children.push(tree2)
                  })
                }
                tree.children.push(tree1)
              })
            }
            this.controls.push(tree)
          })
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    getRoleList() {
      const para = { page: this.dataPage, row: 10 }
      getRoleList(para).then(res => {
        if (res.code == '200') {
          this.dataTotal = res.data.total
          this.tableData = res.data.records
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    changePage(page) {
      this.dataPage = page
      this.getRoleList()
    },
    getRow(val) {
      this.removeIds = []
      this.roleData = val
      val.forEach(item => {
        this.removeIds.push(item.id)
      })
      if (val.length && val.length === 1) {
        this.userId = val[0].id
        lookRoleInfo({ id: val[0].id }).then(res => {
          if (res.code == '200') {
            this.ids = res.data.permissions
          } else {
            this.ids = []
          }
        })
      } else {
        this.ids = []
      }
    },
    authorityEdit(val) {
      this.isDetails = true
      this.name = val.name
      this.code = val.code
      this.remark = val.remark
    },
    handleClose() {
      this.isDialog = false
      this.isDetails = false
    },
    checkMenu(data, currentChecked) {
      const self = this
      const selected = currentChecked.checkedKeys.indexOf(data.id)
      if (selected !== -1) {
        // 统一处理子节点为相同的勾选状态
        self.selectedParent(data)
        if (data.children && data.children.length !== 0) {
          self.uniteChildSame(data, true)
        }
      } else {
        // 未选中 处理子节点全部未选中
        if (data.children && data.children.length !== 0) {
          self.uniteChildSame(data, false)
        }
      }
      self.roleForm.roleMenu = self.$refs.tree.getCheckedKeys()
    },
    uniteChildSame(treeList, isSelected) {
      this.$refs.tree.setChecked(treeList.id, isSelected)
      if (treeList.children && treeList.children.length !== 0) {
        for (let i = 0; i < treeList.children.length; i++) {
          this.uniteChildSame(treeList.children[i], isSelected)
        }
      }
    },
    // 统一处理父节点为选中
    selectedParent(currentObj) {
      const currentNode = this.$refs.tree.getNode(currentObj)
      console.log(currentNode)
      if (currentNode.parent.key !== undefined) {
        this.$refs.tree.setChecked(currentNode.parent, true)
        this.selectedParent(currentNode.parent)
      }
    },
    addLine() {
      this.dialogTitle = '新增角色'
      this.isDialog = true
    },
    changeLine() {
      const self = this
      if (self.roleData.length && self.roleData.length === 1) {
        self.dialogTitle = '修改角色'
        self.isDialog = true
        self.roleForm.name = self.roleData[0].name
        self.roleForm.remark = self.roleData[0].remark
        self.roleForm.code = self.roleData[0].code
        self.roleForm.roleMenu = self.ids
        self.$nextTick(() => {
          self.$refs.tree.setCheckedKeys(self.ids)
        })
      } else {
        self.$message('请先选择一个需要修改的角色！')
      }
    },
    removeLine() {
      if (this.roleData.length) {
        this.$confirm('删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const para = { ids: this.removeIds.toString() }
          removeRole(para).then(res => {
            if (res.code == '200') {
              this.$message({
                type: 'success',
                message: res.message
              })
              this.getRoleList()
            } else {
              this.$message({
                type: 'success',
                message: res.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$message('请先选择需要删除的角色！')
      }
    },
    submitForm(formName) {
      const self = this
      self.$refs[formName].validate((valid) => {
        if (valid) {
          const para = {
            name: self.roleForm.name,
            remark: self.roleForm.remark,
            code: self.roleForm.code,
            menuIds: self.roleForm.roleMenu.toString(),
            parentIds: ''
          }
          if (self.dialogTitle === '新增角色') {
            addRole(para).then(res => {
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getRoleList()
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
              self.isDialog = false
              self.$refs[formName].resetFields()
              self.$nextTick(() => {
                self.$refs.tree.setCheckedKeys([])
              })
            })
          } else if (self.dialogTitle === '修改角色') {
            para.id = self.userId
            updateRole(para).then(res => {
              if (res.code == '200') {
                self.$message({
                  type: 'success',
                  message: res.message
                })
                self.getRoleList()
              } else {
                self.$message({
                  type: 'error',
                  message: res.message
                })
              }
              self.isDialog = false
              self.$refs[formName].resetFields()
              self.$nextTick(() => {
                self.$refs.tree.setCheckedKeys([])
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancleForm(formName) {
      this.isDialog = false
      this.$refs.tree.setCheckedKeys([])
      this.$refs[formName].resetFields()
    },
    viewLine(val) {
      const self = this
      lookRoleInfo({ id: val.id }).then(res => {
        if (res.code == '200') {
          self.isDetails = true
          self.roleName = res.data.name
          self.roleDesc = res.data.remark
          self.roleCode = res.data.code
          self.controls1 = []
          self.controls.forEach(item => {
            const tree = {}
            tree.id = item.id
            tree.label = item.label
            tree.children = []
            tree.disabled = true
            if (item.children && item.children.length) {
              item.children.forEach(item1 => {
                const tree1 = {}
                tree1.id = item1.id
                tree1.label = item1.label
                tree1.children = []
                tree1.disabled = true
                if (item1.children && item1.children.length) {
                  item1.children.forEach(item2 => {
                    const tree2 = {}
                    tree2.id = item2.id
                    tree2.label = item2.label
                    tree2.disabled = true
                    tree1.children.push(tree2)
                  })
                }
                tree.children.push(tree1)
              })
            }
            self.controls1.push(tree)
            self.$nextTick(() => {
              self.$refs.tree1.setCheckedKeys(res.data.permissions)
            })
          })
        } else {
          self.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    },
    findLine() {
      const para = { page: 1, row: 10, keywords: this.findData }
      getRoleList(para).then(res => {
        if (res.code === '200') {
          this.dataTotal = res.datas.total
          this.tableData = res.datas.list
        } else {
          this.$message({
            type: 'error',
            message: res.message
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.paging{
  padding: 15px;
  padding-right: 0;
}
.details-container{
  max-height: 500px;
  overflow: auto;
}
.details-title{
  height: 30px;
  line-height: 30px;
  padding-left: 15px;
}
</style>
